package day2;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class exe1 {
    public static void main(String[] args) {
        demo2();
        int a=0;//统计总次数
        try(FileInputStream fis=new FileInputStream("d://io//textIO.txt");
        ){
        int b;
        while ((b=fis.read())!=-1){//逐字读取
            if(b==65 || b==97){
                a++;
            }
        }
            System.out.println("A与a出现的总次数:"+a);
    }catch (IOException e){
            e.printStackTrace();
        }
}
public static void demo1(){
        try(FileInputStream fis=new FileInputStream("d://io//textIO.txt");
            FileOutputStream fos=new FileOutputStream("d://io//result.txt")
        ){
            Map<Character,Integer> map=new HashMap<>();//集合的泛型不支持基本类型 要写全
            byte[] bs=new byte[1024];
            int len=0;
            while ((len=fis.read(bs))!=-1){
                String s=new String(bs,0,len);
                for(int i=0;i<s.length();i++){
                   char ch=s.charAt(i);//每个字符
                    //如果key值存在，次数加1
                    if(map.containsKey(ch)) map.put(ch, map.get(ch)+1);
                    else map.put(ch,1);
                }
            }
            //处理写入的字符串 结果字符串
            StringBuilder sb=new StringBuilder("最终的结果是：字符(次数)\n");
            for (Character key:map.keySet()){
                Integer value=map.get(key);
                sb.append(key+"("+value+")\n");

            }
            //写入结果字符串
            fos.write(sb.toString().getBytes());
        }catch (IOException e){
            e.printStackTrace();
        }
}
    public static void demo2(){
            try(FileReader fis=new FileReader("d://io//textIO.txt");
                FileWriter fos=new FileWriter("d://io//result.txt")
        ){
            Map<Character,Integer> map=new HashMap<>();//集合的泛型不支持基本类型 要写全
            char[] bs=new char[1024];
            int len=0;
            while ((len=fis.read(bs))!=-1){
                String s=new String(bs,0,len);
                for(int i=0;i<s.length();i++){
                    char ch=bs[i];//每个字符
                    //如果key值存在，次数加1
                    if(map.containsKey(ch)) map.put(ch, map.get(ch)+1);
                    else map.put(ch,1);
                }
            }
            //处理写入的字符串 结果字符串
            StringBuilder sb=new StringBuilder("最终的结果是：字符(次数)\n");
            for (Character key:map.keySet()){
                Integer value=map.get(key);
                sb.append(key+"("+value+")\n");

            }
            //写入结果字符串
            fos.write(sb.toString());
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
